package com.qinghong.scheduling.service;

import com.qinghong.scheduling.config.CronTaskRegistrar;
import com.qinghong.scheduling.config.SchedulingRunnable;
import com.qinghong.scheduling.dao.SysJobRepository;
import com.qinghong.scheduling.model.SysJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysJobService {

    @Autowired
    SysJobRepository sysJobRepository;

    @Autowired
    CronTaskRegistrar cronTaskRegistrar;

    public List<SysJob> getSysJobByStatus(int status) {
        return sysJobRepository.findAllByJobStatus(status);
    }

    public List<SysJob> getAllJobs() {
        return sysJobRepository.findAll();
    }

    public Boolean updateSysJob(SysJob sysJob) {
        SysJob job = sysJobRepository.saveAndFlush(sysJob);
        if (job != null){
            // 更新成功
            SchedulingRunnable runnable = new SchedulingRunnable(sysJob.getBeanName(), sysJob.getMethodName(), sysJob.getMethodParams());
            if (sysJob.getJobStatus() == 1){
                // 定时任务是开启状态
                cronTaskRegistrar.addCronTask(runnable,sysJob.getCronExpression());
            }else {
                // 定时任务是关闭状态，移除定时任务
                cronTaskRegistrar.removeCronTask(runnable);
            }
            return true;
        }else {
            // 定时任务
            return false;
        }
    }
}
